package com.nontax.test.epay.controller;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.nontax.test.common.BaseController;
import com.nontax.test.common.domain.BaseRequest;
import com.nontax.test.common.domain.BaseResponse;
import com.nontax.test.common.domain.VoidResponse;
import com.nontax.test.common.exception.BusinessException;
import com.nontax.test.common.websocket.WebSocketServer;
import com.nontax.test.epay.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import static com.nontax.test.util.StdRestClient.callStdInterface;

@Controller
@RequestMapping("epay")
@Slf4j
public class EpayController extends BaseController {

    @GetMapping("collect.html")
    public ModelAndView collect(ModelAndView view){
        view.setViewName("epay/collect");
        return view;
    }
    @GetMapping("reconcile.html")
    public ModelAndView reconcile(ModelAndView view){
        view.setViewName("epay/reconcile");
        return view;
    }
  @GetMapping("unnowcapital.html")
    public ModelAndView unnowcapital(ModelAndView view){
        view.setViewName("epay/unnowcapital");
        return view;
    }
  @GetMapping("resetpay.html")
    public ModelAndView resetpay(ModelAndView view){
        view.setViewName("epay/resetpay");
        return view;
    }

    /**
     * 发送汇总信息
     */
    @ResponseBody
    @PostMapping("sendCollect")
    public BaseResponse sendCollectInfo(BaseRequest request, AcctFundsCollectInfoDTO acctFundsCollectInfoDTO) throws IOException {
        log.info("前端参数为:{}",JSON.toJSONString(acctFundsCollectInfoDTO));
        StringBuilder sb = new StringBuilder();
        sb.append("前端参数为:").append(JSON.toJSONString(acctFundsCollectInfoDTO));
        String url = generateRequest(request, "/nontax-revenue/financeRest/fundsCollect/acceptAcctFundsCollect.do");
        try {
            callStdInterface(acctFundsCollectInfoDTO, String.class, url, request.getAppId(), request.getAppKey(),getSid());
            return BaseResponse.ok(sb.toString());
        } catch (Exception e) {
            throw new BusinessException("发送失败,"+e);
        }
    }

    /**
     * 发送未明资金信息
     */
    @ResponseBody
    @PostMapping("sendUnknow")
    public BaseResponse sendunknowInfo(BaseRequest request, UnKnownCapitalReceiveDTO unKnownCapitalReceiveDTO){
        log.info("前端参数为:{}",JSON.toJSONString(unKnownCapitalReceiveDTO));
        String url = generateRequest(request, "/nontax-revenue/revenue-rest/unknow.do");
        try {
            unKnownCapitalReceiveDTO.setFid(UUID.randomUUID().toString().replaceAll("-",""));
            unKnownCapitalReceiveDTO.setFfundSerialNo(UUID.randomUUID().toString().replaceAll("-",""));
            unKnownCapitalReceiveDTO.setFreceivedTime("00:00:00");
            unKnownCapitalReceiveDTO.setFpayAcctName("test");
            callStdInterface(unKnownCapitalReceiveDTO, VoidResponse.class, url, request.getAppId(), request.getAppKey(),getSid());
            return BaseResponse.ok();
        } catch (Exception e) {
            throw new BusinessException("发送失败,"+e);
        }
    }


    /**
     * 发送重缴信息信息
     */
    @ResponseBody
    @PostMapping("sendRestPay")
    public BaseResponse sendRestpayInfo(BaseRequest request, AcceptRestPayDTO acceptRestPayDTO){
        log.info("前端参数为:{}",JSON.toJSONString(acceptRestPayDTO));
        String url = generateRequest(request, "/finance-web/revenue-rest//resetPay/acceptResetPayFunds.do");
        try {
            ResetPayFundsInfoDTO resetPayFundsInfoDTO = new ResetPayFundsInfoDTO();
            resetPayFundsInfoDTO.setBank_code(acceptRestPayDTO.getBank_code());
            resetPayFundsInfoDTO.setPay_date(acceptRestPayDTO.getPay_date());
            resetPayFundsInfoDTO.setBatch_no(acceptRestPayDTO.getBatch_no());
            ResetPayFundsInfoDetailDTO resetPayFundsInfoDetailDTO = new ResetPayFundsInfoDetailDTO();
            resetPayFundsInfoDetailDTO.setPay_code(UUID.randomUUID().toString().substring(0,20));
            resetPayFundsInfoDetailDTO.setAmt(new BigDecimal("10"));
            resetPayFundsInfoDetailDTO.setAccount(acceptRestPayDTO.getAccount());
            resetPayFundsInfoDetailDTO.setAccount_type(acceptRestPayDTO.getAccount_type());
            resetPayFundsInfoDetailDTO.setReset_pay_type("1");
            List<ResetPayFundsInfoDetailDTO> detailDTOList = new ArrayList<>();
            detailDTOList.add(resetPayFundsInfoDetailDTO);
            resetPayFundsInfoDTO.setDetails(detailDTOList);
            callStdInterface(resetPayFundsInfoDTO, VoidResponse.class, url, request.getAppId(), request.getAppKey(),getSid());
            return BaseResponse.ok();
        } catch (Exception e) {
            throw new BusinessException("发送失败,"+e);
        }
    }


    /**
     * 发送明细信息
     */
    @ResponseBody
    @PostMapping("/sendReconcile")
    public BaseResponse sendReconcileInfo(BaseRequest request,ReconcileDTO reconcileDTO){
        log.info("前端参数为:{}",JSON.toJSONString(reconcileDTO));
        String url = generateRequest(request, "/nontax-revenue/financeRest/payCapitalReconcile/acceptAcctFundsReconcile.do");
        try {
            if(StringUtils.equals("1",reconcileDTO.getAutoPayCode())){
                //从数据库获取缴款码进行发送
                throw new BusinessException("暂不支持");
            }
            AcctFundsReconcileInfoDTO acctFundsCollectInfoDTO  = new AcctFundsReconcileInfoDTO();
            int packNum = reconcileDTO.getTotalCount() / reconcileDTO.getCurrentCount();
            int lastNum = reconcileDTO.getTotalCount() % reconcileDTO.getCurrentCount();
            String packNo = UUID.randomUUID().toString().replaceAll("-", "");
            for (int i = 0; i < packNum; i++) {
                callStdInterface(generateAcctFundsReconcileInfoDTO(packNum,reconcileDTO,String.valueOf(i+1),packNo), VoidResponse.class, url, request.getAppId(), request.getAppKey(),getSid());
            }
            if(lastNum>0){
                callStdInterface(generateAcctFundsReconcileInfoDTO(packNum,reconcileDTO,String.valueOf(packNum+1),packNo), VoidResponse.class, url, request.getAppId(), request.getAppKey(),getSid());
            }
            return BaseResponse.ok();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    private AcctFundsReconcileInfoDTO generateAcctFundsReconcileInfoDTO(int packNum,ReconcileDTO reconcileDTO,String currentPackNo,String packNo){
        AcctFundsReconcileInfoDTO acctFundsCollectInfoDTO  = new AcctFundsReconcileInfoDTO();
        acctFundsCollectInfoDTO.setChild_pack_num(packNum+"");
        acctFundsCollectInfoDTO.setPay_date(reconcileDTO.getPayDate());
        acctFundsCollectInfoDTO.setBatch_no(reconcileDTO.getBatchNo());
        acctFundsCollectInfoDTO.setPack_no(packNo);
        acctFundsCollectInfoDTO.setCurrent_pack_no(String.valueOf(currentPackNo));
        acctFundsCollectInfoDTO.setTotal_count(reconcileDTO.getTotalCount()+"");
        acctFundsCollectInfoDTO.setBank_code(reconcileDTO.getBankCode());
        acctFundsCollectInfoDTO.setBussiness_type("1");
        List<AcctFundsReconcileInfoDetailDTO> acctFundsReconcileInfoDetailDTOS = new ArrayList<>();
        acctFundsCollectInfoDTO.setCurrent_count(reconcileDTO.getCurrentCount()+"");
        for (int j = 0; j < reconcileDTO.getCurrentCount(); j++) {
            AcctFundsReconcileInfoDetailDTO detailDTO = new AcctFundsReconcileInfoDetailDTO();
            detailDTO.setPay_code(UUID.randomUUID().toString().replaceAll("-","").substring(0,20));
            detailDTO.setAmt(new BigDecimal("10"));
            detailDTO.setAccount(reconcileDTO.getAccount());
            detailDTO.setAccount_type(reconcileDTO.getAccountType());
            acctFundsReconcileInfoDetailDTOS.add(detailDTO);
        }
        acctFundsCollectInfoDTO.setDetails(acctFundsReconcileInfoDetailDTOS);
        return acctFundsCollectInfoDTO;
    }

}
